package com.netease.cloud.cm;

import com.netease.cloud.cm.common.Constants;
import com.netease.cloud.cm.common.DailySummary;
import com.netease.cloud.cm.task.DailyJob;
import com.netease.cloud.cm.task.TestJob;
import com.netease.cloud.cm.util.GetEnvConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.PropertyConfigurator;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.testng.util.Strings;

import java.text.ParseException;
import java.util.concurrent.CountDownLatch;

/**
 * 程序入口
 */
@Slf4j
public class NCMTestMain {

	private static final String DAILY_CRON_EXPR = "0 59 23 * * ?";

	public static void main(String[] args) throws SchedulerException, ParseException {
		PropertyConfigurator.configure(GetEnvConfig.getPath() + "/log4j.properties");
		DailySummary daily = new DailySummary(GetEnvConfig.getEnv());
		log.info("execute successful");

		if (Strings.isNotNullAndNotEmpty(System.getProperty("cron"))) {
			JobDetail testJob = JobBuilder.newJob(TestJob.class)
					.withIdentity("testJob", "testJobGroup")
					.build();
			testJob.getJobDataMap().put(Constants.SUMMARY_KEY, daily);

			// 定义cron表示的任务触发器 for test
			String cronExpression = System.getProperty("cron");
			log.info("Cron Expression is [{}]", cronExpression);
			Trigger testTrigger = TriggerBuilder.newTrigger()
					.withIdentity("testTrigger", "testTriggerGroup")
					.withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
					.build();

			// 定义执行任务 for daliy
			JobDetail dailyJob = JobBuilder.newJob()
					.withIdentity("dailyJob", "testJobGroup")
					.withIdentity(new JobKey("daily"))
					.ofType(DailyJob.class)
					.build();
			dailyJob.getJobDataMap().put(Constants.SUMMARY_KEY, daily);

			// 定义cron表示的任务触发器 for daily
			Trigger dailyTrigger = TriggerBuilder.newTrigger()
					.withIdentity("dailyTrigger", "dailyTriggerGroup")
					.withSchedule(CronScheduleBuilder.cronSchedule(DAILY_CRON_EXPR))
					.build();

			// 定义任务调度器
			SchedulerFactory schedulerFactory = new StdSchedulerFactory();
			Scheduler scheduler = schedulerFactory.getScheduler();

			// 启动调度
			scheduler.scheduleJob(testJob, testTrigger);
			scheduler.scheduleJob(dailyJob, dailyTrigger);
			scheduler.start();

			// wait
			CountDownLatch c = new CountDownLatch(1);
			Runtime.getRuntime().addShutdownHook(new Thread(() -> {
				c.countDown();
				System.out.println("Exited!");
			}));

			try {
				c.await();
			} catch (InterruptedException e) {
				log.error(e.getMessage(), e);
			}

			scheduler.shutdown(true);
		} else {
			new TestJob().execute(null);
		}
		System.exit(0);
	}
}
